<template>
	<view class="content">
		<z-paging ref="paging" v-model="dataList" @query="handleSizeChange" :auto="false" :topZIndex="999"
			:bottomZIndex="10">

			<!-- z-paging默认铺满全屏，此时页面所有view都应放在z-paging标签内，否则会被盖住 -->
			<!-- 需要固定在页面顶部的view请通过slot="top"插入，包括自定义的导航栏 -->
			<template #top>
				<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true"
					leftIconColor="#fff">
					<view slot="right">
						<m-bubble type="list" :selectData="formMenus" position="right" topOpsotion="right"
							bgcRgba="#fff" color="#333" @selectFun="TapPopup">
							<u-icon name="more-dot-fill" color="#fff" class="moremenu"></u-icon>
						</m-bubble>
					</view>
				</u-navbar>

				<view class="search x-bc">
					<u-search :placeholder="searchPlaceHolder" v-model="keyword" shape="square"
						:ShowScan="$utils.isPda()" @search="$refs.paging.reload()">
						<template #action>
							<view class="x-c">
								<u-icon v-if="!$utils.isPda()" name="scan" color="#fff" size="30"
									@click="searchScanBtn"></u-icon>
							</view>
						</template>
					</u-search>
				</view>


				<view class="MenuBoxMax">
					<view class="f-dc MenuBox">

						<m-dropdown ref="mDropdown" titleSize="14px" menuIconSize="14px" height="40"
							active-color="#51d0d0" :style="{'overflow': stickShow ? 'hidden' : ''}"
							@open="mDropdownOpen" @close="stickShow = true">
							<!-- 时间选择 -->
							<m-dropdown-item v-for="row in queryColumns" :key="row.colName" v-if="row.colType==3"
								:rowInfo="row" :title="queryConditions[row.colName + '_show'] || row.colDesc">
								<template #desc="{element}">
									<view
										style="background-color: #f2f2f2;padding: 6px 15px;color: #999;font-size: 12px;">
										{{element.colDesc}}
									</view>
								</template>

								<m-date-time :InitData="DropDowmMenu_Date[row.colName]"
									@DateSubmit="DateSubmit($event,row)"></m-date-time>

								<view style="background-color: #fff;padding: 4px 10px;">
									<button @tap="resetTimeBtn(row)">重置</button>
								</view>
							</m-dropdown-item>

							<!-- 项目选择 -->
							<m-dropdown-item v-for="row in queryColumns" v-if="row.colType==2 && row.selDetail.type<3"
								:title="MenuTitleBack(row)" :rowInfo="row" v-model="queryConditions[row.colName]"
								:format="{label:'text',icon:'icon',value:'value'}" :options="getQuerySelectColumns(row)"
								@change="changeValue($event,row)" @reset="MenuResetBtn">
								<template #desc="{element}">
									<view
										style="background-color: #f2f2f2;padding: 6px 15px;color: #999;font-size: 12px;">
										{{element.colDesc}}
									</view>
								</template>
							</m-dropdown-item>


							<view slot="filter" class="selectSearchDom x-c">

								<view v-if="sortOptions.length" class="x-c"
									style="padding:0 10px;border-left:1px solid #cdcdcd;height:100%">
									<!-- 排序 -->
									<uni-icons fontFamily="CustomFontPlatform" style="font-weight: 600;" color="#818181"
										@click="OpenSortPopup"
										:class="sortData.Sort.value.toLowerCase() == 'desc' ? '' : 'icon-flip-vertical'"
										:size="20">{{ $utils.toUniCode('&#xe7e9;')}}</uni-icons>
								</view>

								<!-- <view v-if="queryColumns.length" class="x-c" -->
								<view v-if="showMenuFilterFun()" class="x-c"
									style="padding:0 10px;color:#818181;height:100%;" @click="choiceParams">
									<!-- 筛选 -->
									<uni-icons fontFamily="CustomFontPlatform" color="#818181"
										:size="20">{{$utils.toUniCode('&#xe6cb;')}}</uni-icons>
								</view>
							</view>
						</m-dropdown>

					</view>

				</view>

			</template>

			<view class="MainBox">
				<!-- <view class="content_main_CardBox" v-for="(item,index) in dataList" :key="item[ShowKeyName]" -->
				<view class="content_main_CardBox" v-for="(item,index) in dataList" :key="index"
					style="margin-bottom: 10rpx;">

					<view class="x-bc content_main_CardBox_TopBox" @click="toggleSelection(item)">
						<view class="x-f">
							<checkbox class="CheckBox" style="margin-right: 6px;" v-if="ShowSelect"
								:checked="item.checked" color="#fff" activeBackgroundColor="#51d0d0"
								activeBorderColor="#51d0d0">
							</checkbox>
							<view>
								<text class="content_main_CardBox_TopBox_TitleName"
									style="font-size: 28rpx;">{{item[titleCol.colName]}}</text>
							</view>
						</view>


						<view class="TagBox x-ec">
							<u-tag class="theTag" :text="item[tag.colName]" v-for="tag in tagCols"
								style="margin-left: 10rpx;" size="mini" plain plainFill
								:type="showTagStatus(item[tag.colName])"></u-tag>
						</view>

					</view>

					<view class="x-bc" @click.stop="ToIndex(item)">

						<view class="formBox" style="flex: 1;">
							<!-- <view class="FiledBox" v-for="col in columns"
								v-if="!col.isHidden && !col.isTitle && !col.isFold && isShowColumns(col)">
								<text class="FiledBox_label_f24 FiledBox_grifola">{{col.colDesc}}:</text>
								<text
									class="FiledBox_value FiledBox_value_f24 FiledBox_grifola">{{item[col.colName]}}</text>
							</view> -->

							<view v-for="col in newColumn">

								<view class="FiledBox">
									<text class="FiledBox_label_f24 FiledBox_grifola">{{col.colDesc}}:</text>
									<text
										class="FiledBox_value FiledBox_value_f24 FiledBox_grifola">{{item[col.colName]}}</text>
								</view>

							</view>
						</view>

						<view class="x-ec">
							<view class="priceBox">
							</view>

							<view v-if="listType != 'wait'">
								<u-icon name="arrow-right" color="#cbcbcb" size="16"></u-icon>
							</view>
						</view>

					</view>
				</view>
			</view>

			<template #bottom>
				<view class="bottomTool x-bc" :style="$utils.disposeSafeBottomFun()">
					<view class="operTotal" @click="OpenSelectCellPopup">

						<view v-if="!ShowSelect" class="FiledBox" style="width: fit-content;">
							<text class="FiledBox_grifola">
								<text>共计笔数</text>
								<text style="margin: 0 4px;">{{paging.totalCount}}</text>
								<text>笔</text>
							</text>
						</view>

						<view v-else>
							已选：{{selectedData.length}}
						</view>
					</view>
					<view class="operBtn">
						<u-row gutter="10" v-if="!ShowSelect">
							<u-col span="6" v-if="workList.length">

								<m-bubble type="list" :selectData="workList" :showOverlay="false" position="right"
									topOpsotion="center" boxPosition="bottom" bgcRgba="#fff" color="#333"
									@selectFun="topMoreBtn">
									<u-button class="CommonBtnSize" plain hairline text="更多"></u-button>
								</m-bubble>
							</u-col>
							<u-col span="6" v-if="btn_showCondition() && btnAllowShowFun('新增')">
								<u-button class="CommonBtnSize" type="primary" text="新增" @click="insertNew"></u-button>
							</u-col>
						</u-row>

						<u-row gutter="10" v-else>
							<u-col span="6">
								<u-button class="CommonBtnSize" type="info" plain hairline text="取消"
									@click="cancelBtn"></u-button>
							</u-col>
							<u-col span="6">
								<u-button class="CommonBtnSize" type="primary" :throttleTime="2000"
									:text="ButtonInfo.name" @click="tapMoreBtn"></u-button>
							</u-col>
						</u-row>

					</view>


				</view>

			</template>


		</z-paging>
		<uni-popup ref="popup" @close="closeSelect" type="right">
			<view class="f-dc" style="width: 80vw;height: 100%;background-color: #e8e8e8;"
				:style="$utils.disposeSafeBottomFun()">
				<u-navbar :fixed="false" title="筛选" :autoBack="false" leftIcon=" " :safeAreaInsetTop="true"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeSelect"></uni-icons>
					</view>
				</u-navbar>
				<view class="FilterBox">

					<view class="FiledBox x-bc" style="padding: 15rpx 20rpx;backgroundColor: #fff;"
						v-for="row in queryColumns" v-if="row.colType==2 && row.selDetail.type==3"
						@click="openBaseScreen(row)">
						<text class="FiledBox_label_x15 FiledBox_grifola" style="color: #333;">{{row.colDesc}}</text>

						<view class="x-ec">
							<text class="FiledBox_value FiledBox_value_x14 FiledBox_grifola"
								style="color: #585858;">{{queryConditions[row.colName+'_show']}}</text>

							<uni-icons type="right" size="18" color="#999"></uni-icons>
						</view>
					</view>
				</view>

				<view style="padding: 10px;background:#fff;">
					<u-row :gutter="10">
						<u-col span="6">
							<u-button text="重置" @click="resetBtn"></u-button>
						</u-col>
						<u-col span="6">
							<u-button type="primary" text="确定" @click="$refs.paging.reload();closeSelect()"></u-button>
						</u-col>
					</u-row>
				</view>

			</view>
		</uni-popup>



		<!-- 排序弹层 -->
		<uni-popup ref="popup_sort" type="bottom" background-color="#ffffff" @close="closeSortPopup">
			<view class="f-dc" style="max-height: 80vh;" :style="$utils.disposeSafeBottomFun()">
				<u-navbar :fixed="false" title="排序" :autoBack="false" leftIcon=" " :safeAreaInsetTop="false"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeSortPopup"></uni-icons>
					</view>
				</u-navbar>

				<view class="MainBox" style="padding: 15px;flex: 1;overflow: auto;padding-bottom: 20px;">
					<m-sort :sortOptions="sortOptions" :format="sortFormat" :defaultSort="defaultSort"
						:selectSort="sortData.Sort" @change="handleSortChange"></m-sort>
				</view>
			</view>
		</uni-popup>


		<!-- 已选数据弹层 -->
		<uni-popup ref="popup_select" type="bottom" background-color="#ffffff" @close="closeSelectPopup">
			<view class="f-dc" style="height: 50vh;" :style="$utils.disposeSafeBottomFun()">
				<u-navbar :fixed="false" title="已选中数据" :autoBack="false" leftIcon=" " :safeAreaInsetTop="false"
					leftIconColor="#fff" style="width: 100%;">
					<view class="u-nav-slot" slot="right">
						<uni-icons color="#fff" type="close" size="30" @click="closeSelectPopup"></uni-icons>
					</view>
				</u-navbar>

				<view class="MainBox" style="padding: 4px 6px;flex: 1;overflow: auto;padding-bottom: 20px;">
					<view class="x-bc" style="padding: 10px;border-bottom: 1rpx solid #f7f7f7;"
						v-for="(item,index) in selectedData" :key="item[keyName]">
						<text>{{item.BillNO}}</text>

						<uni-icons type="trash-filled" color="#ff0e0e" size="24"
							@click="deleteSelect(item,index)"></uni-icons>

					</view>
				</view>
			</view>
		</uni-popup>


		<m-pda-scancode v-if="$utils.isPda()" listenName="listScanCode"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>
	</view>

</template>

<script>
	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;

	// var vm;
	export default {
		data() {
			return {
				ShowKeyName: '', // 列表key
				stickShow: false,
				DropDowmMenu_Date: { // 时间下拉
					// DateTitle: '全部',
					// SDate: '',
					// EDate: '',
				},

				titleName: '', // 标题名称
				moduleName: '', // 模块名称-（如：销售订单）
				columns: [], // 列表字段配置项 
				workList: [], // 原生二开按钮
				crudList: [], // 二开业务按钮
				params: [],
				titleCol: {}, // 列表标题项
				keyName: '', // 主键ID （如：SoOrderID）
				queryColumns: [], // 筛选项字段配置
				tagCols: [], // 状态标签（如：审核通过）
				paging: { // 分页数据设置
					pageSize: 30,
					pageIndex: 1,
					totalCount: 0
				},
				searchPlaceHolder: '', // 搜索文字提示
				keyword: '', // 搜索字段
				queryConditions: {}, // 选中下拉项数据
				formMenus: [{ // 右侧气泡选项数据
						name: '单据设置',
						value: '',
						icon: 'order',
						show: true,
					},
					{
						name: '刷新',
						value: '',
						icon: 'reload',
						show: true,
					},
					{
						name: '草稿箱',
						value: '',
						icon: 'file-text',
						show: true,
					}
				],
				dataList: [], // 列表数据
				lastCallCom: 0, // 节流变量


				sortOptions: [], // 排序数据
				sortFormat: { // 排序字段定义
					id: 'id',
					name: 'colDesc',
					text: 'text',
					value: 'value',
				},
				sortData: { // 选中的排序数据
					OrderBy: '',
					Sort: {
						value: ''
					},
				},
				sortFields: [{ // 升降序数据
						text: '升序',
						value: 'ASC'
					},
					{
						text: '降序',
						value: 'DESC'
					}
				],
				defaultSort: null, // 默认选中的排序id

				selectedData: [], // 选中的数据  
				ShowSelect: false, // 是否开启多选
				ButtonInfo: {}, // 选中按钮的数据详情

				listType: '', // 列表类型
				pageNo: 1,

				//审批配置流程
				approvalConfig: {},
				approveObj: {},

				APPRoleCol: [], // 需要隐藏字段权限数据
			}
		},
		onReady() {},
		onShow() {},
		onLoad(option) {
			var that = this;
			let vm = this;


			if (this.$utils.isEmpty(option)) {
				this.listType = 'list';
			} else {
				this.listType = option.type;
			}


			// 判断当前APFunName是否存在草稿数据
			// 所有数据

			//获取当前页面对象
			let menuObj = this.$store.state.Menu;


			setTimeout(() => {
				// 获取指定模块的权限数据
				that.$store.commit('GetUnPermissionConfigInfo', {
					moduleName: menuObj.APFunName,
				});

				// 根据APP表单名称获取所属权限
				// that.$store.dispatch('GetAPPRoleColFunByRoleID', {
				// 	moduleName: menuObj.APFunName,
				// 	moduleType: 'formlist',
				// }).then(res => {
				// 	console.log(res);
				// 	if (res.status == 200) {
				// 		that.APPRoleCol = res.data.ds;
				// 	}
				// }).catch((err) => {
				// 	console.log(err)

				// })
				try {

					that.$request("getAPPRoleColFunByRoleID", {
						moduleName: menuObj.APFunName,
						moduleType: 'formlist',
					}, (res) => {
						if (res.status == 200) {
							that.APPRoleCol = res.data.ds;
						} else {
							layer.alert(JSON.stringify(res))
						}
					}, err => {
						layer.alert(JSON.stringify(err))
					})
				} catch (err) {

				}


				// console.log(JSON.stringify(menuObj));
				that.titleName = menuObj.APFunName + '列表';
				that.moduleName = menuObj.Para;
				// setZPXConfig({
				//     'default-page-size': 30,
				//     'empty-text': '查无数据',
				//     //...
				// });


				that.initConfig(that.moduleName);
			}, 50);

		},
		watch: {

		},
		computed: {
			newColumn() {
				let filterData = this.columns.filter(col => {
					return !col.isHidden && !col.isTitle && !col.isFold && this.isShowColumns(col)
				});
				return filterData
			}
		},
		mounted() {
			let vm = this;
			let that = this;
			if (that.$utils.isPda()) {
				uni.$on('listScanCode', function(content) {
					that.$utils.showLoading('正在解码');
					that.getMainInfo(content);
				})
			}

			// 监听刷新
			uni.$on('FormInitToRefresh', (data) => {
				that.refreshToPageFun(data.keyID);
			})

			//弹窗下拉数据选择
			uni.$on('selectPicker_formList', function(data) {
				//单选下直接赋值
				var curCol = vm.columns.filter(function(item) {
					return item.colName == data.colName
				});
				vm.queryConditions[data.colName] = data.data[curCol[0].selDetail.hiddenValue];
				vm.queryConditions[data.colName + '_show'] = data.data[curCol[0].selDetail.displayValue];
				vm.$forceUpdate();
			})

			// 组件中监听队列完成
			this.$onQueueEvent('queueEmpty', () => {

			});

			this.$onQueueEvent('requestFail', (ret) => {
				if (process.env.NODE_ENV === 'development') {
					layer.alert(JSON.stringify(ret), {
						title: "请求失败，请联系开发人员",
						cancelText: "确定",
					}, function(ret) {

					});
				} else {
					layer.alert("请求失败，请联系开发人员", {
						title: "提示",
						cancelText: "确定",
					}, function(ret) {

					});
				}

			});
		},
		onUnload() { // 监听页面卸载,
			uni.$off('FormInitToRefresh');
			uni.$off('listScanCode');
			uni.$off('selectPicker_formList');

			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'MenuDetail',
				data: {}
			});
		},
		methods: {
			btnAllowShowFun(str) { // 判断当前按钮是否允许显示
				let data = this.$store.state.appConfigInfo.filterUnPermissionConfig;
				let flash = data.some(item => item.FunName == str);
				return !flash;
			},
			post(sql, param, callBack) {
				let vm = this;
				param["sql"] = sql;
				if (vm.Request.getUserInfo()) {
					if (!param.hasOwnProperty("P_UserID")) {
						param.P_UserID = vm.Request.getUserInfo().UserID;
					}
					if (!param.hasOwnProperty("P_UserName")) {
						param.P_UserName = vm.Request.getUserInfo().UserName;
					}
					if (!param.hasOwnProperty("P_UserCode")) {
						param.P_UserCode = vm.Request.getUserInfo().UserCode;
					}
				}
				vm.Request.requestByUrl("/SQLData/QuerySql", param, function(data) {
					callBack(data);
				}, function(err) {
					console.log(err)
				});
			},

			//按钮显示条件判断
			btn_showCondition() {
				try {
					var _this = this;
					var result = true;
					var showScript = _this.crudList[0].show;

					if (showScript) {
						eval("result=(" + showScript + ")");
					}
					return result;
				} catch (e) {
					return false;
				}
			},
			showMenuFilterFun() {
				return this.queryColumns.some(item => item.colType == 2 && item.selDetail?.type == 3);
			},
			refreshToPageFun(dataId) { // 刷新列表数据至指定页。
				let vm = this;
				vm.$refs.paging.refreshToPage(vm.pageNo).then(ret => {

					//状态标签
					var tagCols = vm.columns.filter(function(item) {
						return item.isFold == true
					});

					let filterData = ret.totalList.filter(item => {
						return item[vm.keyName] == dataId
					})
					if (filterData.length) {

						let tagColumnsInfo = []
						tagColumnsInfo = tagCols.map(function(tag) {
							return {
								text: filterData[0][tag.colName],
								type: vm.showTagStatus(filterData[0][tag.colName])
							}
						});

						// 找到对应的数据，回写给index页面
						uni.$emit('newListData', {
							data: tagColumnsInfo
						})
					}

				}).catch((err) => {
					console.log(err)
				});
			},
			cellDataBackFun(data) {
				let that = this;
				let filterData = data.filter(col => {
					return !col.isHidden && !col.isTitle && !col.isFold && that.isShowColumns(col)
				})

				return filterData
			},
			OpenSortPopup() { // 点击打开排序 
				this.$refs.popup_sort.open()

			},
			closeSortPopup() {
				this.$refs.popup_sort.close()
			},
			handleSortChange(sortData) { // 选中排序
				let vm = this;
				const {
					sort: {
						colName,
						id
					},
					item
				} = sortData;

				this.params.defaultOrder = `${colName} ${item.value}`;
				this.closeSortPopup();
				this.$refs.paging.reload();

				setTimeout(() => {
					vm.sortData.OrderBy = colName;
					vm.defaultSort = id;
					vm.sortData.Sort = item;
				}, 500);
			},

			cancelBtn() { // 点击取消
				let vm = this;
				vm.ShowSelect = false;
				vm.selectedData = [];
				vm.ButtonInfo = {};
				vm.dataList.map(item => {
					item.checked = false;
				})
			},
			tapMoreBtn() { // 点击自定义按钮
				let vm = this;


				if (!vm.selectedData.length) {
					layer.msg('至少选中一条数据')
					return;
				}

				vm.$utils.showLoading();

				if (vm.ButtonInfo.script) {
					function task1() {
						return new Promise((resolve, reject) => {
							eval(vm.ButtonInfo.script);

							// resolve();
						});
					}

					function task2() {
						return new Promise((resolve, reject) => {
							vm.cancelBtn();
							resolve();
						});
					}
					task1().then((ret) => {
						return task2();
					}).then(() => {
						vm.$utils.hideLoading();
					}).catch((error) => {
						vm.$utils.hideLoading();
						uni.showToast({
							title: error,
							icon: 'error'
						})
						console.error('An error occurred:', error);
					});

				} else {
					vm.$utils.hideLoading();
					layer.msg('脚本未定义');
					vm.ShowSelect = false;
				}
			},
			topMoreBtn(data) { // 点击更多按钮
				// layer.msg('111111222344')
				// 开启多选
				this.ShowSelect = true;

				this.ButtonInfo = data;

			},
			toggleSelection(item) { // 点击checked选项
				item.checked = !item.checked;

				if (item.checked) {
					this.selectedData.push(item);
				} else {
					const index = this.selectedData.findIndex(row => row[vm.keyName] === item[vm.keyName]);
					this.selectedData.splice(index, 1);
				}
			},
			OpenSelectCellPopup() { // 打开已选中的数据项弹层
				if (this.selectedData.length == 0) {
					return
				}

				this.$refs.popup_select.open();
			},
			closeSelectPopup() {
				this.$refs.popup_select.close();
			},
			deleteSelect(data, index) {
				this.selectedData.splice(index, 1);
				const itemToUncheck = this.dataList.find(item => item[vm.keyName] === data[vm.keyName]);
				if (itemToUncheck) {
					itemToUncheck.checked = false;
				}


				if (this.selectedData.length == 0) {
					this.closeSelectPopup();
				}
			},

			mDropdownOpen() { // 下拉框打开时触发
				this.stickShow = false;
			},

			DateSubmit(data, row) { // 选中时间
				if (this.$utils.isEmpty(data.SDate)) {
					if (row.colName in this.queryConditions) {
						delete this.queryConditions[row.colName]
					}

				} else {
					this.queryConditions[row.colName] = data.SDate + '->' + data.EDate;
				}
				this.queryConditions[row.colName + '_show'] = data.DateTitle;

				this.DropDowmMenu_Date[row.colName] = this.$utils.deepClone(data);

				// Object.assign(this.DropDowmMenu_Date[row.colName], data)
				this.$refs.mDropdown.close();
				this.$refs.paging.reload()
			},
			MenuTitleBack(row) {
				let FilterData = this.getQuerySelectColumns(row).filter(item => {
					return item.value == this.queryConditions[row.colName];
				});
				if (FilterData.length) {
					// console.log(FilterData)
					return FilterData[0]['text'];
				} else {
					// console.log(row)
					return row.colDesc || '请选择'
				}
			},
			changeValue(data, row) { // 切换普通下拉cell选项

				this.queryConditions[row.colName] = data.value;
				this.queryConditions[row.colName + '_show'] = data.text;

				this.$refs.paging.reload()
			},
			MenuResetBtn(data) { // 普通下拉cell的重置按钮

				if (this.queryConditions.hasOwnProperty(data.colName)) {
					delete this.queryConditions[data.colName];
				}

				this.$refs.mDropdown.close();
				this.$refs.paging.reload()
			},
			initConfig(objName) {
				let vm = this;
				var that = this;
				that.$requestByUrl('/AppFormList/GetDataByName', {
					objName: objName
				}, function(data) {
					// 清除选中数据
					vm.selectedData = [];
					// 清除下拉筛选项
					vm.queryConditions = {};

					var filterCondition = data.ds[0]["filterCondition"];
					if (filterCondition == null) {
						filterCondition = "";
					}

					if (data.ds[0]["columnsConfig"]) {

						let getKeyData = JSON.parse(data.ds[0]["columnsConfig"])

						let filterKeyData = getKeyData.filter(item => item.isKey);

						if (filterKeyData.length) {
							vm.ShowKeyName = filterKeyData[0]['colName']
						}

					}

					function evaluateShowCondition(conditionStr) {
						// 这里使用 eval() 是不安全的，仅作为示例  
						// 在实际应用中，应避免使用 eval() 评估用户输入  
						try {
							return eval(conditionStr);
						} catch (e) {
							return false; // 如果条件字符串无效，默认返回 false  
						}
					};

					let worksConfigData = JSON.parse(data.ds[0]["worksConfig"])
					const filteredArray = worksConfigData.filter(item => evaluateShowCondition(item
						.show));


					that.tableConfig({
						columns: JSON.parse(data.ds[0]["columnsConfig"]),
						workList: filteredArray,
						crudList: JSON.parse(data.ds[0]["crudConfig"]),
						params: {
							isFormList: data.ds[0]["isFormList"],
							physicalTableName: data.ds[0]["physicalTableName"],
							isPaging: data.ds[0]["isPaging"],
							filterCondition: filterCondition,
							defaultOrder: data.ds[0]["defaultOrder"],
							detailName: data.ds[0]["detailName"],
							isFormEdit: false,
							rowClassCol: data.ds[0]["rowClassCol"],
							onReadyCallBack: data.ds[0]["onReadyCallBack"],
							colClassCol: data.ds[0]["colClassCol"],
						}
					})
				}, err => {
					layer.alert(JSON.stringify(err))
				})
			},
			tableConfig(options) {
				let vm = this;
				// vm.columns = options.columns;
				// 这里需要对colums进行映射处理，处理权限字段显示问题

				const aDataMap = new Map();
				if (Array.isArray(this.APPRoleCol)) {
					for (const row of this.APPRoleCol) {
						if (row?.ColName !== undefined) {
							aDataMap.set(row.ColName, row);
						}
					}
				}

				if (Array.isArray(options?.columns)) {
					for (const item of options.columns) {
						const colName = item?.colName;
						if (colName) {
							const typeInfo = aDataMap.get(colName);
							if (typeInfo) {
								const {
									IsViewRole,
									IsEditRole
								} = typeInfo;
								item.isHidden = !IsViewRole;
								item.isReadOnly = !IsViewRole && !IsEditRole;
							}
						}
					}
				}
				vm.columns = options.columns;

				vm.workList = options.workList;
				vm.crudList = options.crudList;
				vm.params = options.params;

				//vm.openLoading();
				//初始化查询控件
				var titleCols = vm.columns.filter(function(item) {
					return item.isTitle == true
				});
				if (titleCols.length > 0) {
					vm.titleCol = titleCols[0];
				};
				//状态标签
				var tagCols = vm.columns.filter(function(item) {
					return item.isFold == true
				});
				vm.tagCols = tagCols;

				var keyName = "";
				var keyValue = "";
				var keyColumn = vm.columns.filter(function(item) {
					return item.isKey == true
				});
				if (keyColumn.length > 0) {
					vm.keyName = keyColumn[0].colName;
				};

				vm.initSelectValue();
				var queryColumns = vm.columns.filter(function(item) {
					// return item.isColQuery == true && item.isTitle == false
					return item.isColQuery == true
				});

				// DropDowmMenu_Date
				let backDate = queryColumns.filter(row => row.colType == 3)

				let customValue = {
					DateTitle: '',
					SDate: '',
					EDate: '',
				}

				let newObject = backDate.reduce((acc, curr) => {
					// 将当前对象的 colName 作为新对象的属性名  
					// 将自定义的对象作为属性值  
					acc[curr.colName] = customValue;
					return acc;
				}, {});

				vm.DropDowmMenu_Date = vm.$utils.deepClone(newObject);

				vm.queryColumns = queryColumns;
				//文字搜索框内容
				vm.searchPlaceHolder = vm.queryColumns.filter(function(item) {
					return item.colType == 1;
				}).map(function(item) {
					return item.colDesc;
				}).join('/');

				// 过滤出属于排序的数据
				let sortOptions = queryColumns.filter(item => item.isOrder)
				vm.sortOptions = sortOptions.map((item, index) => {
					return {
						...item,
						id: index,
					}
				});

				let SortType = vm.params.defaultOrder.split(' ');

				if (SortType.length == 1) {
					SortType.push('desc')
				}

				// 找到对应的排数数据
				let defaultData = sortOptions.filter(item => {
					return item.colName == SortType[0]
				})
				if (defaultData.length) {
					vm.sortData.OrderBy = SortType[0];
					vm.defaultSort = defaultData[0]['id'];
					vm.sortData.Sort = vm.sortFields.filter(item => (item.value).toUpperCase() == (SortType[1])
						.toUpperCase())[0];
				}



				this.$refs.paging.reload();
				// vm.handleSizeChange(1, 30);
			},
			//分页事件
			handleSizeChange(pageNo, pageSize) {
				let vm = this;
				vm.$utils.showLoading();
				var queryColumns = [];
				var filterCondition = ' 1=1 ';
				for (var i = 0; i < vm.queryColumns.length; i++) {
					if (vm.queryConditions[vm.queryColumns[i].colName] != null && vm.queryConditions[vm.queryColumns[i]
							.colName] != undefined) {
						let colName = vm.queryColumns[i].colName;
						//日期类型
						if (vm.queryColumns[i].colType == 3) {
							let dates = vm.queryConditions[colName].split('->');
							filterCondition += ' and DATEDIFF(day, \'' + dates[0].toString() + '\',' + colName +
								')>=0 and DATEDIFF(day, ' + colName + ', \'' + dates[1].toString() + '\')>=0  ';
						} else if (vm.queryColumns[i].colType == 2) {
							filterCondition += ' and ' + colName + '=\'' + vm.queryConditions[colName] + '\' '
						} else if (vm.queryColumns[i].colType == 4) {
							filterCondition += ' and ' + colName + '=\'' + vm.queryConditions[colName] + '\' '
						}
						// else {
						// 	filterCondition += ' and ' + colName + ' like \'%' + vm.queryConditions[colName] + '%\' '
						// }
					}
				}

				let searchQuerys = vm.queryColumns.filter(function(item) {
					return item.colType == 1;
				})
				if (searchQuerys.length) {
					let keywordFilter = ' 1<>1 ';
					searchQuerys.forEach(function(item) {
						keywordFilter += ' or ' + item.colName + ' like \'%' + vm.keyword + '%\' '
					})
					filterCondition += " and (" + keywordFilter + ")";
				}


				// if (vm.queryConditions[vm.titleCol.colName]) {
				// 	filterCondition += ' and ' + vm.titleCol.colName + ' like \'%' + vm.queryConditions[vm.titleCol
				// 		.colName] + '%\' '
				// }
				if (vm.params.filterCondition) {
					filterCondition += ' and ' + vm.params.filterCondition;
				}
				//查询

				vm.pageNo = pageNo;
				let searchObj = {
					tableName: vm.params.physicalTableName,
					columnsStr: JSON.stringify(queryColumns),
					currentCol: '',
					pageIndex: pageNo,
					pageSize: +pageSize,
					isForm: (vm.params.isFormList || true).toString(),
					filterCondition: filterCondition,
					defaultOrder: vm.params.defaultOrder || ''
				}

				console.log(searchObj);
				vm.$requestByUrl('/SQLData/GetDataByPhysicalTableNameByQueryPaging_Uniapp', searchObj,
					function(data) {
						if (vm.selectedData.length) {
							// 如果有已选中数据，给对应列回显  

							let selectedIDs = vm.selectedData.map(item => {
								return item[vm.keyName]
							});

							let comparisonSoOrderIDs = new Set(selectedIDs); // 直接使用Set来存储需要匹配的SoOrderID  

							data.ds.forEach(item => {
								item.checked = comparisonSoOrderIDs.has(item[vm
									.keyName]); // 直接使用has的结果来设置checked  
							});

						} else {
							// 如果没有已选中数据，将所有项的checked设置为false  
							// 这里我们直接修改原数组中的对象，而不是创建一个新数组  
							data.ds.forEach(item => {
								item.checked = false;
							});
						};

						vm.$utils.hideLoading(1000);

						if (data.ds1.length > 0) {
							//绑定总长度
							vm.paging.totalCount = parseInt(data.ds1[0]["@TotalCount"]);
						}
						vm.paging.pageIndex = vm.paging.pageIndex + 1;
						vm.$refs.paging.completeByTotal(data.ds, vm.paging.totalCount);

					},
					function(err) {
						console.log(err)

						vm.$refs.paging.completeByTotal(vm.dataList, 0);
					});
			},
			resetTimeBtn(row) { // 重置时间
				let vm = this;

				// 判断是否存在重置的时间字符
				if (vm.queryConditions.hasOwnProperty(row.colName)) {
					if (!vm.$utils.isEmpty(vm.DropDowmMenu_Date)) {
						for (const key in vm.DropDowmMenu_Date) {
							if (vm.DropDowmMenu_Date.hasOwnProperty(key)) {
								if (key == row.colName) {

									const item = vm.DropDowmMenu_Date[key];
									item['SDate'] = '';
									item['EDate'] = '';
									item['DateTitle'] = '';
								}
							}
						}

					}
					delete vm.queryConditions[row.colName];
					delete vm.queryConditions[row.colName + '_show'];
				}

				this.$refs.mDropdown.close();
				this.$refs.paging.reload()

			},
			resetBtn() { // 筛选-重置按钮
				let vm = this;
				// vm.queryColumns = {};
				// 处理时间问题

				if (!vm.$utils.isEmpty(vm.DropDowmMenu_Date)) {
					for (const key in vm.DropDowmMenu_Date) {
						if (vm.DropDowmMenu_Date.hasOwnProperty(key)) {
							const item = vm.DropDowmMenu_Date[key];
							item['SDate'] = '';
							item['EDate'] = '';
							item['DateTitle'] = '';
						}
					}
				}

				vm.queryConditions = {};

			},
			isShowColumns(colObj) {
				var that = this;
				var showColumns = uni.getStorageSync(that.moduleName + '_ShowColumns');
				var isShow = true;
				if (showColumns) {
					let flag = showColumns.some(item => item == colObj.colName)
					if (!flag) {
						isShow = false;
					}
				}
				return isShow;
			},
			//获取查询下拉数据源	
			getQuerySelectColumns(row) {
				let MapData = row.selDetail.sqlDataSource.map(function(item) {
					return {
						text: item[row.selDetail.displayValue],
						value: item[row.selDetail.hiddenValue]
					}
				});
				return MapData
			},
			getMinDate(strInterval1, Number1) {
				var date;
				date = new Date();
				Date.prototype.DateAdd = function(strInterval, Number) {
					var dtTmp = this;
					switch (strInterval) {
						case 's':
							return new Date(Date.parse(dtTmp) + (1000 * Number));
						case 'n':
							return new Date(Date.parse(dtTmp) + (60000 * Number));
						case 'h':
							return new Date(Date.parse(dtTmp) + (3600000 * Number));
						case 'd':
							return new Date(Date.parse(dtTmp) + (86400000 * Number));
						case 'w':
							return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
						case 'q':
							return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(),
								dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
						case 'm':
							return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp
								.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
						case 'y':
							return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp
								.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
					}
				}
				return date.DateAdd(strInterval1, Number1);
			},
			//初始化下拉数据源
			initSelectValue() {
				let vm = this;
				var requestSelectSql = []
				for (var i = 0; i < vm.columns.length; i++) {
					//下拉控件
					if (vm.columns[i].colType == 2) {
						//普通下拉
						if (vm.columns[i].selDetail.type == 1) {
							var sql = vm.columns[i].selDetail.dataSource;
							vm.columns[i].selDetail.sqlDataSource = [];
							vm.columns[i].selDetail.originDataSource = [];

							var requestSql = vm.Request.PromiseRequestByUrl('/SQLData/GetDataBySql', {
								sql: sql
							});
							requestSelectSql.push({
								index: i,
								request: requestSql
							});
						}
					}
				}
				requestSelectSql.forEach(function(item) {
					item.request.promise.then(function(data) {
						vm.$set(vm.columns[item.index].selDetail, "sqlDataSource", data.data.ds);
						vm.$set(vm.columns[item.index].selDetail, "originDataSource", data.data.ds);
					})
				})
			},
			searchScanBtn() { // 搜索栏扫码
				let that = this;

				/* uni.scanCode({
					success: function(res) {
						that.getMainInfo(res.result);
					}
				}); */
				this.$scanPopup.openScan({
					success: (res) => {
						that.getMainInfo(res.result);
					}
				})
			},
			getMainInfo(data) { // 给输入框赋值
				this.keyword = data;

				this.$utils.hideLoading();
			},
			//显示标签颜色状态
			showTagStatus(tagName) {
				if (tagName.indexOf('通过') >= 0 || tagName.indexOf('成功') >= 0) {
					return "success";
				} else {
					return "warning";
				}
			},
			queryList() {
				let that = this;

				that.$utils.showLoading();

				let data = []


				that.$refs.paging.complete(data);
			},
			TapPopup(data) { // 选中气泡项
				let vm = this;

				switch (data.name) {
					case '单据设置':
						//传递当前列给到列表和表头设置
						vm.$store.commit('ChangeAndSetStateData', {
							Name1: 'FormColumnSetting',
							data: vm.columns
						});

						uni.navigateTo({
							url: '/commonPage/Form/FieldSetting',
							events: {
								reloadPage: function(ret) {
									if (!vm.$utils.isEmpty(ret)) {

										vm.columns = ret.map(item => {
											const {
												isShow,
												...rest
											} = item;
											return rest;
										});
									}

									vm.$refs.paging.refresh();
								}
							}
						})
						break;
					case '刷新':
						vm.$refs.paging.reload();
						break;
					case '草稿箱':
						// 跳转到草稿箱列表
						uni.navigateTo({
							url: '/commonPage/Form/draftList' + '?titleName=' + this.titleName.replace('列表', '')
						})

						break;
					default:
						break;
				}

			},
			//新增
			insertNew() {
				let vm = this;
				var that = this;
				//查看详情
				var returnData = {
					detailTitle: vm.titleName,
					detailName: vm.params.detailName,
					keyName: vm.keyName,
					keyValue: 0,
					dataInfo: {
						//titleColName: obj[that.titleCol.colName],
					}
				}

				vm.$store.commit('ChangeAndSetStateData', {
					Name1: 'MenuDetail',
					data: returnData
				});


				uni.navigateTo({
					url: '/commonPage/Form/Edit'
				})
			},
			ToIndex(obj) {
				var that = this;
				let vm = this;

				if (this.ShowSelect) {
					this.toggleSelection(obj)
					return
				};

				if (vm.listType == 'wait') { // 待办
					return
				}


				function throttle(fn, delay = 3000) {
					return function(...args) {
						const now = new Date().getTime();
						if (now - that.lastCallCom < delay) {
							return;
						}
						that.lastCallCom = now;
						fn.apply(this, args);
					};
				}

				throttle(function() {



					if (vm.listType == 'audit') { // 待审核
						let returnData = {
							detailTitle: vm.titleName,
							detailName: obj['B_KeyDetail'],
							keyName: obj['B_KeyCol'],
							keyValue: obj['BillID'],
							dataInfo: {
								titleColName: '',
								showColumnsInfo: [],
								tagColumnsInfo: [],
							}
						}

						vm.$store.commit('ChangeAndSetStateData', {
							Name1: 'MenuDetail',
							data: returnData
						});

						uni.navigateTo({
							url: '/commonPage/Form/Edit',
							success() {
								that.lastCallCom = 0;
							}
						})

					} else {
						//查看详情
						let returnData = {
							detailTitle: vm.titleName,
							detailName: vm.params.detailName,
							keyName: vm.keyName,
							keyValue: obj[vm.keyName],
							dataInfo: {
								titleColName: obj[that.titleCol.colName],
							}
						};

						var showColumnsInfo = [];
						showColumnsInfo = that.columns.filter(function(col) {
							return !col.isHidden && !col.isTitle && !col.isFold && that.isShowColumns(col);
						}).map(function(col) {
							return {
								name: col.colDesc,
								value: obj[col.colName]
							}
						})

						var tagColumnsInfo = []
						tagColumnsInfo = that.tagCols.map(function(tag) {
							return {
								text: obj[tag.colName],
								type: that.showTagStatus(obj[tag.colName])
							}
						});


						returnData.dataInfo["showColumnsInfo"] = showColumnsInfo;
						returnData.dataInfo["tagColumnsInfo"] = tagColumnsInfo;


						vm.$store.commit('ChangeAndSetStateData', {
							Name1: 'MenuDetail',
							data: returnData
						});


						uni.navigateTo({
							url: '/commonPage/Form/index',
							success() {
								that.lastCallCom = 0;
							}
						})
					}


				}, 2000)();
			},
			choiceParams() {
				this.$refs.popup.open('right')
			},
			closeSelect() {
				this.$refs.popup.close()
			},
			openBaseScreen(row) {
				let vm = this;
				var obj = {
					chooseType: row.selDetail.chooseType,
					allowClear: true,
					showSearch: true,
					searchKey: row.selDetail.displayValue,
					serverSearch: true,
					displayValue: row.selDetail.displayValue,
					hiddenValue: row.selDetail.hiddenValue,
					parentValue: row.selDetail.parentValue,
					isPaging: true,
					sql: row.selDetail.dataSource,
					name: row.colDesc,
					colName: row.colName,
					param: {},
					treeObj: {
						treeDataSource: row.selDetail.treeDataSource,
						treeDisplayValue: row.selDetail.treeDisplayValue,
						treeHiddenValue: row.selDetail.treeHiddenValue,
						treeParentValues: row.selDetail.treeParentValues,
					}
				}
				obj.param[row.selDetail.displayValue] = "";

				vm.$store.commit('ChangeAndSetStateData', {
					Name1: 'SelectPickerSetting',
					data: obj
				});

				uni.navigateTo({
					// url: '/commonPage/Tool/selectPicker'
					url: '/commonPage/Tool/selectPicker' + '?pickerListen=selectPicker_formList'
				})
			}
		}
	}
</script>


<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		// height: calc(100vh - 60px);
		// background-color: #f9f9f9;
		background-color: #f2f2f2;

		.icon-flip-vertical {
			display: inline-block;
			/* 或者其他适合你的布局的display值 */
			transform: scaleY(-1);
			/* 垂直翻转 */
		}

		uni-button {
			margin-left: initial !important;
			margin-right: initial !important;
		}

		.MainPopup {
			flex: initial !important;

			.PopupContent {
				display: flex;
				flex-direction: column;
				min-height: 240px;
				width: 90vw;
			}

			.u-transition {
				z-index: 99999 !important;
			}


			.PopupMainBox {
				padding: 12px 10px 6px;
				flex: 1;
				// overflow: auto;

				.CellBox {
					margin-bottom: 20px;

					.LeftBox {
						font-size: 14px;
						color: #999;
						margin-right: 10px;
					}
				}

				.uni-input-placeholder {
					color: #6a6a6a !important;
					font-size: 12px !important;
				}
			}

			.PopupBottomBox {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 10px 10px;

				.CancelBtn {
					background-color: #fff;
					color: #51d0d0;
					border: 1px solid #51d0d0;
					min-width: 80px;
				}

				.ComfirmBtn {
					background-color: #51d0d0;
					color: #fff;
					min-width: 80px;
					margin-left: 10px !important;
				}
			}
		}

		.MenuBoxMax {
			position: relative;
			height: 42px;
			width: 100%;
			border-bottom: 4px solid #f2f2f2;

			.MenuBox {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				background-color: #fff;

				.selectSearchDom {
					padding-right: 10rpx;
				}
			}
		}

		.MainBox {
			// flex: 1;
			// overflow: auto;
			padding: 10rpx;

			// 表单1
			.u-form {
				// padding: 0px 10px;

				.u-form-item {
					background-color: #fff;
					padding: 0 16px;
				}


				.TopOption {

					.u-form-item__body {
						flex-direction: column !important;
					}
				}

				// 起止时间
				.ChoiceTimesBox {
					width: 100%;
					display: flex;
					align-items: center;
					// background-color: #fff;
					// padding: 18px 10px;
					// margin-top: 10px;

					.TimeBox {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-evenly;

						.timer {
							width: 100%;
							flex: 2;
							display: flex;
							flex-direction: column;
							// align-items: center;
							font-size: 16px;
							color: #333;

							text:first-child {
								margin-bottom: 10px;
								font-weight: 600;
							}

							text:last-child {
								height: 20px;
							}
						}

						.Icon {
							flex: 1;
						}
					}
				}


				// 上传-删除图标
				.u-upload__deletable {
					width: 20px;
					height: 20px;

					.u-upload__deletable__icon {
						right: -1px !important;

						.u-icon__icon {
							font-size: 20px !important;
							line-height: 16px !important;
						}
					}
				}
			}
		}

		.BottomBox {
			width: 100%;
			// height: 70px;
			// line-height: 70px;
			padding: 6px 15px;
			border-top: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;
			// padding-bottom: constant(safe-area-inset-bottom) !important;
			// padding-bottom: env(safe-area-inset-bottom) !important;
		}

		.moremenu {
			margin-right: 10rpx;
		}

		.search {
			background-color: #fff;
			background-color: #51d0d0;
			padding: 6px 10px;

			.scanQrCode {
				width: 20rpx;
				padding: 5rpx;
			}
		}

		.list {
			background-color: #999;
		}

		.bottomTool {
			background: #fff;
			padding: 15rpx;
			border-top: 2px solid #f2f2f2;
		}

		.operTotal {
			font-size: 14px;
			color: #333;
		}

		.operBtn {
			width: fit-content;
		}

		.FilterBox {
			flex: 1;

			.FiledBox {
				position: relative;

				&::after {
					position: absolute;
					box-sizing: border-box;
					content: ' ';
					pointer-events: none;
					right: 16px;
					bottom: 0;
					left: 16px;
					border-bottom: 1px solid #ebedf0;
					-webkit-transform: scaleY(0.5);
					transform: scaleY(0.5);
				}

				&:last-child::after {
					border-bottom: none;
				}
			}
		}
	}
</style>